package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResponse<RoleVo> queryPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        String roleName = role.getRoleName();
        PageHelper.startPage(pageNum,pageSize);
        Page<Role> page = roleMapper.queryPage(roleName);
        PageResponse<RoleVo> roleVoPageResponse = PageResponse.of(page, RoleVo.class);
        return roleVoPageResponse;
    }

    @Override
    public void insert(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<String> findCheckedResourcesByRoleId(Long roleId) {
        return roleMapper.findCheckedResourcesByRoleId(roleId);
    }

    @Override
    public void editAndStatusAndResource(RoleDto roleDto) {
        //1.角色修改和启用禁用
        Role role = BeanUtil.toBean(roleDto, Role.class);
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();

        if(ObjectUtil.isEmpty(checkedResourceNos)){
            roleMapper.update(role);
            return;
        }

        //对于菜单权限的分配修改，先根据roleid全部删除，再依次添加
        roleMapper.deleAllByRoleId(role.getId());

        for (int i = 0; i < checkedResourceNos.length; i++) {
            RoleResource roleResource = new RoleResource();
            roleResource.setResourceNo(checkedResourceNos[i]);
            roleResource.setRoleId(role.getId());
            roleResource.setDataState("0");
            roleMapper.insertRoleAndResource(roleResource);
        }
    }
}
